/*
 * Copyright (C) 2022 KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */

#include "appiconimageprovider.h"
#include <QIcon>
#include <QGSettings>
#include <QMutex>
#include <QMutexLocker>
#include <KIconTheme>
#include <QDebug>

extern QMutex qiconMutex;

AppIconImageProvider::AppIconImageProvider()
    : QQuickImageProvider(QQuickImageProvider::Pixmap)
{

}

AppIconImageProvider::~AppIconImageProvider()
{
}

QPixmap AppIconImageProvider::requestPixmap(const QString &id, QSize *size, const QSize &requestedSize)
{
    Q_UNUSED(size)
    if (id.startsWith("file#")) {
        auto items = id.split("#");
        if (items.size() < 2) {
            qWarning() << "AppIconImageProvider: app icon id error, " << id;
            return QPixmap(xDesktopAppIcon());
        }

        return QPixmap(items.at(1));
    }

    if (id.startsWith("theme#")) {
        auto items = id.split("#");
        if (items.size() < 3) {
            qWarning() << "AppIconImageProvider: app icon id error, " << id;
            return QPixmap(xDesktopAppIcon());
        }
        QMutexLocker locker(&qiconMutex);
        QString iconName = items.last();
        QIcon icon = QIcon::fromTheme(iconName);
        return icon.pixmap(requestedSize.width(), requestedSize.height());
    }

    return QPixmap();
}

QString AppIconImageProvider::xDesktopAppIcon()
{
    QGSettings iconStyle("org.ukui.style");
    QString iconThemeName;

    if (iconStyle.keys().contains("iconThemeName")) {
        iconThemeName = iconStyle.get("iconThemeName").toString();
    }
    KIconTheme iconInfo(iconThemeName);
    return iconInfo.iconPathByName("application-x-desktop", 96, KIconLoader::MatchBest);
}
